
$(function(){
    let _deleteIds = null, _action = '/add',_row = null;
    const _convertor = {type:[]};
    const alerter = Frame2.alert.init({$div:$('#alertbar')});
    const table = $('#table').bootstrapTable({
        url: _DIR + '/table',
        method: 'POST',
        toolbar:'#formbar',
        pagination: true,
        sidePagination: 'server',//服务器端分页 返回数据 {rows:[],total:1}
        pageNumber: 1,
        pageSize: 15,
        pageList: [15, 20, 50, 100],//分页步进值
        columns: [
            {checkbox: true, valign: "bottom"},
            {
                showSelectTitle:true,
                field: 'id',
                title: 'ID',sortable:true
            }, {
                field: 'title',
                title: '标题'
            }, {
                field: 'author',
                title: '作者/分类'
            }, {
                field: 'content',
                title: '篇幅',
                formatter: (value, row, index, field) => {
                    if (value)
                        return value.length;
                    else
                        return 0;
                }
            }, {
                field: 'content',
                title: '内容',
                formatter: (value, row, index, field) => {
                    if (value.length > 30)
                        return value.substr(0,30) + "...";
                    else
                        return value;
                }
            }, {
                title:'操作',
                align: 'center',
                class: 'action',
                formatter: (value, row, index, field) => {
                    var btn = '<button type="button" class="btn btn-xs btn-success view" title="点击查看详情">查看</button>'
                        +'<button type="button" class="btn btn-xs btn-primary update">修改</button>'
                        +'<button type="button" class="btn btn-xs btn-warning read">朗读</button>'
                        +'<button type="button" class="btn btn-xs btn-danger del">删除</button>';
                    return btn;
                },
                events:{
                    'click .view': function(e,value,row,index){
                        var view = $('#viewModal');
                        view.find("#view_title").text(row.title);
                        view.find("#view_content").text(row.content);
                        view.find('#view_createTime').text(new Date(row.createTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                        view.find('#view_updateTime').text(new Date(row.updateTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                        view.find("#view_description").text(row.description);
                        view.modal('show');
                    },
                    'click .update': function(e,value,row,index) {
                        var form = $('#addForm'),modal = $('#addModal');
                        _action = '/update';
                        modal.find('.modal-title').text('修改小说');
                        form.find("[name='id']").val(row.id);
                        form.find("[name='title']").val(row.title);
                        form.find("[name='author']").val(row.author);
                        form.find("[name='content']").val(row.content);
                        form.find("[name='description']").val(row.description);

                        modal.modal('show');
                        form.data('bootstrapValidator').resetForm();
                        //alert(form.data('bootstrapValidator').isValid())
                    },
                    'click .read': function(e,value,row,index){
                        reader.changer(row);
                    },
                    'click .del': function(e,value,row,index){
                        _deleteIds = [row.id];
                        $('#deleteModal').modal('show');
                    },
                }
            }
        ],
        queryParams:function(params) {
            var $array = $('#formbar').serializeArray();
            $.each($array, function(index, val) {
                if(val.value && val.value.trim())
                    params[val.name]=val.value.trim();
            });
            return params;
        },
    });

    $('#listbar').on('click', '.add', function(event) {
        event.preventDefault();
        var form = $('#addForm'),modal = $('#addModal');
        form.find("[name='id']").val(0);
        form.find("[name='title']").val('');
        form.find("#text1").val('');
        _action = '/add';
        modal.find('.modal-title').text('新增小说');
        modal.modal('show');
    });
    $('#listbar').on('click', '.del', function(event) {
        event.preventDefault();
        _deleteIds = Frame2.bootstrap.getSelectionsAttr(table,'id');
        if (_deleteIds == null || _deleteIds.length == 0) {
            alerter.show(100,function(){},{autohide:3000,title:'提示：',content:'请选择要删除的数据！'})
        } else{
            $('#deleteModal').modal('show');
        };
    });
    $('#readbar').on('click', '.stop', function(event) {
        event.preventDefault();
        reader.stop();
    });
    //确认删除事件
    $('#deleteModal').on('click', '.del', function(event) {
        event.preventDefault();
        $.ajax({
            url: _DIR + '/delete',
            type: 'POST',
            dataType: 'json',
            traditional:true,
            data: {ids: _deleteIds},
            success: function(result) {
                $('#deleteModal').modal('hide');
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'数据删除成功。'})
                    table.bootstrapTable('refresh');
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            },complete: function(){
                _deleteIds = [];
            }
        });
    });
    $('#addForm').on('click', '#handleText', function(event) {
        var text = $('#text1').val().trim();
        if (text.length==0) {
            alert('no text to handle');
            return;
        }
        $('#text1').val(text.replace(/[\r\n ]/g,""))
    });
    $('#addForm').on('click', '#handleFilter', function(event) {
        var text = $('#text1').val().trim();
        if (text.length==0) {
            alert('no text to handle');
            return;
        }
        var filter = $('#filter').val().trim();
        if (filter.length==0) {
            return;
        }
        $('#text1').val(text.replace(new RegExp(filter, 'g'),""))
    });

    //新增表单验证+提交
    $('#addForm').bootstrapValidator(Frame2.bootstrap.validatorConfig({
        fields:{
            title: {
                message: '角色名不合法',//默认提示信息
                validators: {
                    notEmpty: {
                        message: '小说标题不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 20,
                        message: '小说标题必须是2-20个字符'
                    }
                }
            }
        }
    })).on('success.form.bv', function(e) {
        e.preventDefault();
        let form = $(e.target);
        $.ajax({
            url: _DIR + _action,
            type: 'POST',
            dataType: 'json',
            data: form.serialize(),
            success: function(result) {
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'操作成功。'})
                    $('#addModal').modal('hide');
                    table.bootstrapTable('refresh');
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            }
        });
        return false;
    });

    const reader ={
        id: 0,
        content: '',
        index: -1,
        audio: null,
        len:200,
        tts: 'https://ss0.baidu.com/6KAZsjip0QIZ8tyhnq/text2audio?cuid=dict&lan=ZH&ctp=1&pdt=30&',
        init: function (audio) {
            let _ = this;
            _.audio = audio;
            audio.onended = function(){
                _.read()
            }
        },
        // 切换小说
        changer: function(row) {
            let _ = this;
            if (_.id==row.id) {//重复点击正在朗读的小说
                _.index
                ;
                _.read()
            } else {
                _.id = row.id;
                _.content = row.content;
                _.index = 0;
                _.read()
            };
        },
        read: function() {
            let _ = this;
            if (_.index==-1) {
                alert('无可读内容，或已经朗读完成!');
                _.id=0;
                _.content='';
                return;
            } else if (!_.content){
                alert('无可读内容!');
                _.id=0;
                return;
            };
            //alert(_content)
            let content='', start=this.index*this.len, len=this.len;
            if (start+this.len > this.content.length) {
                len=this.content.length-start;
                this.index = -1;
            } else{
                this.index++;
            };
            content=this.content.substr(start, len);
            //_reader.indexSpan.innerText=start + ' + ' + len + '<' + this.content.length + '>'
            let tts = $('#ttsForm').serialize();

            _.audio.src = this.tts + tts + '&tex=' + content;
            _.audio.play()
        },
        stop: function () {
            let _ = this;
            _.audio.pause();
            _.id = 0;
            _.content = '';
            _.index = -1;
        }
    }
    reader.init($('#audio').get(0))
});
